package cn.org.cute.ebocy.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 * OBJECT 和 byte[]互转方法类
 * @Copyright©2011, 2011 EBO CHANGYOU Co.td. All rights reserved.
 * @Version 1.0.0
 * @since jdk1.6
 * @author xiaolei
 * @date 2011-12-6
 */
public class ByteToObjectUtil {
	
	/**
	 * 将Object转化为byte[]
	 * @param IntoObj 需要转化的Object对象
	 * @return
	 */
	public static byte[] objectToByte(Object IntoObj) {
		byte[] bytes = null;
		try {
			// object to bytearray
			ByteArrayOutputStream bo = new ByteArrayOutputStream();
			ObjectOutputStream oo = new ObjectOutputStream(bo);
			oo.writeObject(IntoObj);

			bytes = bo.toByteArray();

			bo.close();
			oo.close();
		} catch (Exception e) {
			System.err.println("ObjectToByte-->" + e.getMessage());
			e.printStackTrace();
		}
		return bytes;
	}
	
	
	
    /**
     * 将byte[]转化为Object对象
     * @param bytes 转化前的byte[]
     * @return
     */
	public static Object byteToObject(byte[] bytes) {
		Object intoObject = null;
		try {
			// bytearray to object
			ByteArrayInputStream bi = new ByteArrayInputStream(bytes);
			ObjectInputStream oi = new ObjectInputStream(bi);

			intoObject = oi.readObject();

			bi.close();
			oi.close();
		} catch (Exception e) {
			System.err.println("objectToByte-->" + e.getMessage());
			e.printStackTrace();
		}
		return intoObject;
	}
	

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}

}
